package view.Core;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class selectUpdateTreeActivity extends Activity {
	EditText select_tree_to_editText1;
	Button select_tree_to_button1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_tree_to_update);

		findTreeByID();

	}

	public void onSelectTree(View view) {
		selectAllFromTree();

	}

	public void selectAllFromTree() {
		String reply;
		String ans = "";
		try {
			// String url =
			// "http://192.168.1.101/oldTreeWeb/getJsonField.php?Name=Tree tat";

			String url = getResources().getString(R.string.serverURL)
					+ "getJsonByTreeID.php?inputTreeID="
					+ select_tree_to_editText1.getText().toString();
			// getJsonByTreeID.php
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet(url);
			HttpResponse response = client.execute(request);

			String line = "";
			reply = "";
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			while ((line = reader.readLine()) != null) {
				reply = line;
			}
			reader.close();
			try {

				JSONArray json = new JSONArray(reply);

				// toastMsg(""+json.toString());
				JSONArray jsonArrayB = new JSONArray(json.getString(0));
				String getField = jsonArrayB.getString(0);

				JSONObject jsonField = new JSONObject(getField);

				ans = jsonField.getString("treeID");

				Intent i = new Intent();
				i.putExtra("treeID", ans);
				i.setClass(this, treeDataUpdate.class);
				startActivity(i);
				
			} catch (JSONException e) {
				toastMsg("" + e);
			}
		} catch (Exception e) {
			toastMsg("" + e);
		}
	}

	public void toastMsg(String toast) {
		Toast.makeText(this, toast, Toast.LENGTH_LONG).show();
	}

	public void findTreeByID() {
		select_tree_to_editText1 = (EditText) findViewById(R.id.select_tree_to_editText1);
		select_tree_to_button1 = (Button) findViewById(R.id.select_tree_to_button1);
	}
}